package test2.redis;

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import redis.clients.jedis.Jedis;

public class LuaRedisLockTest {
	
	static long timeout = 3000;
	static String lockscript = FileUtil.readfile("lock.lua");
	static String unlockscript = FileUtil.readfile("unlock.lua");
	static String key = "demokey";
	static String ttl = "10000";
	static String key2 = "tv";
	static String key3 = "buytv";
	
	static ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	
	public static void main(String[] args) throws InterruptedException {
		Jedis jedis = new Jedis();
		jedis.set(key2, "4");
		jedis.del(key3);
		jedis.close();
		
		for(int i=0;i<50;i++) {
			threadpool.submit(new Runnable() {
				@Override
				public void run() {
					String value = System.currentTimeMillis()+"";
					if(lock(value)) {
						int stock = Integer.parseInt(jedis.get(key2));
						if(stock>0) {
							jedis.decr(key2);
							System.err.println("恭喜你，你是第"+jedis.incr(key3)+"个抢购成功的用户");
						} else {
							System.err.println("已经被抢光");
						}
					} else {
						System.out.println("锁失败");
					}
					releaseLock(value);
				}
			});
		}
//		jedis.close();
		threadpool.shutdown();
	}
		
	static boolean lock(String value) {
		long start = System.currentTimeMillis();
		while(true) {
			Jedis jedis = new Jedis();
			try {
				long ret = (long)jedis.eval(lockscript
							, Arrays.asList(new String[]{key})
							, Arrays.asList(new String[]{value, ttl}));
				if(ret==1) break;
				long current = System.currentTimeMillis();
				if(current-start>timeout) return false;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				jedis.close();
			}
		}
		System.out.println("锁成功");
		return true;
	}
	
	static void releaseLock(String value) {
		Jedis jedis = new Jedis();
		try {
			long ret= (long)jedis.eval(unlockscript
						, Arrays.asList(new String[]{key})
						, Arrays.asList(new String[]{value}));
			System.out.println(ret==1?"解锁成功":"已经被解锁");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jedis.close();
		}
	}

}
